<?php

namespace app\logic;

use app\model\Admin;
use app\model\Log;
use think\Collection;

class LogLogic
{
    /**
     * @var Log
     */
    private Log $logModel;

    /**
     * @param Log $logModel
     */
    public function __construct(Log $logModel)
    {
        $this->logModel = $logModel;
    }

    /**
     * 写入日志
     *
     * @param Admin $adminInfo
     * @param string $type
     * @param string $remark
     * @param int $level
     * @param array $additional
     */
    public function writeLog(Admin $adminInfo, string $type, string $remark, int $level = 0, array $additional = [])
    {
        $data = [
            'type'    => $type,
            'optid'   => $adminInfo['id'],
            'optname' => $adminInfo['name'],
            'remark'  => $remark,
            'optdt'   => date('Y-m-d H:i:s'),
            'ip'      => getClientIP(),
            'web'     => getBrowser(),
            'level'   => $level
        ];

        foreach ($additional as $key => $value) {
            $data[$key] = $value;
        }

        $this->logModel->insert($data);
    }

    /**
     * 查询日志
     *
     * @param array|string $where
     * @return array|Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public
    function queryLogs(array|string $where): array|Collection
    {
        return $this->logModel->where($where)->select();
    }

    /**
     * 获取登录失败次数
     *
     * @param string $device
     * @return int
     * @throws \think\db\exception\DbException
     */
    public
    function getLoginFailedCount(string $device): int
    {
        return $this->logModel->where([
            ['level', '=', 3],
            ['device', '=', $device],
            ['optdt', '>', date('Y-m-d H:i:s', time() - 5 * 60)]
        ])->count();
    }
}